<template>
  <div>
    <v-header></v-header>
    <el-form :model="registerForm" ref="registerForm" class="registerContainer" status-icon :rules="rules" @keyup.enter.native="submitForm('registerForm')">
      <el-form-item>
        <el-row>
          <el-col :span="12">
            <router-link to='login' style="text-decoration: none;color: #000000">
              <div class="grid-content bg-purple" style="text-align: center;font-size: 20px;">
                登录
              </div>
            </router-link>
          </el-col>
          <el-col :span="12">
            <router-link to='register' style="text-decoration: none;">
              <div class="grid-content bg-purple-light" style="text-align: center;font-size: 20px;color: #409EFF;border-bottom: 2px solid #409EFF;">
                注册
              </div>
            </router-link>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item prop="username">
        <el-input v-model="registerForm.username" auto-complete="false" type="text" prefix-icon="el-icon-user" placeholder="给自己一个响亮的名字吧" class="inputContainer"></el-input>
      </el-form-item >
      <el-form-item prop="pass">
        <el-input v-model="registerForm.pass" auto-complete="false" type="password" prefix-icon="el-icon-lock" placeholder="请输入密码" class="inputContainer" @input="passwordTest()"></el-input>
      </el-form-item>
      <el-form-item prop="checkPass">
        <el-input v-model="registerForm.checkPass" auto-complete="false" type="password" prefix-icon="el-icon-lock" placeholder="请确认密码" class="inputContainer"></el-input>
      </el-form-item>
      <el-form-item prop="email">
        <el-input v-model="registerForm.email" prefix-icon="el-icon-message" placeholder="请输入邮箱" ref="email" class="inputContainer"></el-input>
      </el-form-item>
      <el-form-item prop="emailCode" style="display: inline">
        <el-input v-model="registerForm.emailCode" style="width: 150px" prefix-icon="el-icon-postcard" placeholder="请输入验证码" class="inputContainer"></el-input>
        <el-button type="primary" size="medium" :disabled="disable" :class="{ codeGeting:isGeting }" @click="getVerifyCode('registerForm')" style="font-size: 14px;margin-left: 10px;">{{getCode}}</el-button>
        <span style="margin-left: 10px" v-html="icon"></span>
<!--        <i class="el-icon-loading"></i>-->
      </el-form-item>
      <div style="margin-top: 15px">
        <span style="font-size: 14px;margin-top: 10px;color: #8f8b8b">密码强度:</span>
        <span :style="defaultClass" style="margin-left: 10px">{{passPower}}</span>
      </div>
      <el-form-item>
        <el-button type="primary" @click="submitForm('registerForm')" style="width: 100%;margin-top: 10px" class="inputContainer">提交</el-button>
        <el-button @click="resetForm('registerForm')" style="width: 100%;margin-left:0;margin-top: 10px" class="inputContainer">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import header from "../layout/Header";
import footer from "../layout/Footer";

export default {
  components: {
    'v-header': header,
    'v-footer': footer
  },
  name: 'Login',
  data() {
    const checkUserName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户名'))
      } else {
        if (value.length < 2 || value.length > 16) {
          callback(new Error('用户名长度在2到16位'))
        }
        callback()
      }
    };
    let validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (value.length < 8 || value.length > 32) {
          callback(new Error('密码长度必须在8到32位之间'))
        } else if (this.registerForm.checkPass !== '') {
          this.$refs.registerForm.validateField('checkPass')
        }
        callback()
      }
    };
    let validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.registerForm.pass) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    };
    let checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的邮箱格式'))
        }
      }, 100)
    };
    let checkEmailCode = (rules, value, callback) => {
      if (value === '') {
        callback(new Error('验证码不能为空'))
      } else {
        callback()
      }
    };
    return {
      registerForm: {
        email: '',
        emailCode: '',
        username: '',
        pass: '',
        checkPass: '',
        check: ''
      },
      passPower: '',
      defaultClass: { color: 'black', 'font-size': '14px' },
      ok: { color: '#37ff71', 'font-size': '14px', 'font-weight': 'bold' },
      warn: { color: '#ffdb1d', 'font-size': '14px', 'font-weight': 'bold' },
      error: { color: '#e52204', 'font-size': '14px', 'font-weight': 'bold' },
      icon: '',
      getCode: '获取验证码',
      isGeting: false,
      count: 60,
      disable: false,
      rules: {
        username: [
          { validator: checkUserName, trigger: 'blur' }
        ],
        pass: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ],
        email: [
          { validator: checkEmail, trigger: 'blur' }
        ],
        emailCode: [
          { validator: checkEmailCode, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    document.title = '注册';
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios({
            method: 'post',
            url: '/user/before/register',
            dataType: 'json',
            data: {
              email: this.registerForm.email,
              emailCode: this.registerForm.emailCode,
              username: this.registerForm.username,
              pass: this.registerForm.pass,
              check: this.registerForm.check
            }
          }).then((res) => {
            if (res.data.msgCode === '200') {
              this.$message({
                message: res.data.msg,
                type: 'success'
              });
              this.$router.push('/login');
            } else {
              this.$message({
                message: res.data.msg,
                type: 'error'
              });
            }
            console.log(res.data);
          })
        } else {
          console.log('error submit!!');
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    getVerifyCode (formName) {
      this.icon = '<i class="el-icon-loading"></i>';
      this.$refs[formName].validateField('email', valid => {
        if (!valid) {
          let countDown = setInterval(() => {
            if (this.count < 1) {
              this.isGeting = false;
              this.disable = false;
              this.getCode = '获取验证码';
              this.count = 60;
              clearInterval(countDown)
            } else {
              this.isGeting = true;
              this.disable = true;
              this.getCode = this.count-- + 's后重发';
            }
          }, 1000);
          this.$axios({
            method: 'post',
            url: '/user/before/getEmailCode',
            dataType: 'json',
            contentType: 'application/json',
            data: {
              email: this.registerForm.email
            }
          }).then((res) => {
            console.log(res.data);
            if (res.data.msgCode === '200') {
              this.icon = '<i class="el-icon-circle-check"></i>';
              this.$message({
                message: res.data.msg,
                type: 'success'
              });
            } else {
              this.$message({
                message: res.data.msg,
                type: 'warning'
              });
            }
          })
        } else {
          console.log('error submit!!');
          return false
        }
      })
    },
    passwordTest() {
      let strongRegex = new RegExp('^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$', 'g');
      let mediumRegex = new RegExp('^(?=.{8,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$', 'g');
      // eslint-disable-next-line no-unused-vars
      let enoughRegex = new RegExp('(?=.{8,}).*', 'g');
      let pass = this.registerForm.pass;

      if (strongRegex.test(pass)) {
        this.passPower = '安全';
        this.defaultClass = this.ok;
      } else if (mediumRegex.test(pass)) {
        this.passPower = '一般';
        this.defaultClass = this.warn;
      } else {
        this.passPower = '不安全';
        this.defaultClass = this.error;
      }
    }
  }
}
</script>

<style>
  .registerContainer{
    border-radius: 15px;
    background-clip: padding-box;
    margin: 30px auto;
    width: 350px;
    padding: 15px 35px 15px 35px;
    background: #fff;
    border: 1px solid #eeeeee;
    box-shadow: 0 0 25px #cac6c6;
  }
  .inputContainer{
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)
  }
</style>
